package com.sf.sms.user.action;

import com.sf.sms.user.entity.User;
import com.sf.sms.user.service.IMsUserBiz;
import com.sf.sms.utils.SmsContants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by 80002004 on 2016/8/29.
 */
@Controller
@RequestMapping("/authorization")
public class AuthorzationAction {

    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private IMsUserBiz userBiz;

    @RequestMapping("/login")
    public String tologin() {
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()) {
            return "/index";
        }
        return "auth/login";
    }

    @RequestMapping("/auth")
    public String authorzation(HttpSession session,
                               @RequestParam(required = true) String userName,
                               @RequestParam(required = true) String passWord,
                               Model model) {
        User user = userBiz.findByName(userName);

        UsernamePasswordToken upToken = new UsernamePasswordToken(userName, /*Encodes.decodeBase64(passWord).toString().toCharArray()*/passWord);
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(upToken);
        } catch(UnknownAccountException ex) {
            logger.error(ex.toString());
            setLoginInfo(model, userName, SmsContants.EX_INFO_USERNAME);
            model.addAttribute("errorMsg","用户名不存在！");
            return "auth/login";
        } catch (IncorrectCredentialsException ex) {
            logger.error(ex.toString());
            setLoginInfo(model, userName, SmsContants.EX_INFO_PASSWORD);
            model.addAttribute("errorMsg","密码错误！");
            return "auth/login";
        } catch(LockedAccountException ex) {
            logger.error(ex.toString());
            setLoginInfo(model, userName, SmsContants.EX_INFO_USERNAME);
            model.addAttribute("errorMsg","账号已锁定，无法登陆，请联系管理员！");
            return "auth/login";
        } catch (AuthenticationException ex) {
            logger.error(ex.toString());
            setLoginInfo(model, userName, SmsContants.EX_INFO_USERNAME);
            model.addAttribute("errorMsg","登陆异常！");
            return "auth/login";
        } catch (Exception ex) {
            logger.error(ex.toString());
            setLoginInfo(model, userName, SmsContants.EX_INFO_USERNAME);
            model.addAttribute("errorMsg","登陆错误，请联系管理员！");
            return "auth/login";
        }
        /**调试*/
        User user2 = (User)subject.getSession().getAttribute("currentUser");
        String url = (String)session.getAttribute("PRE_URL");
        logger.info("AuthorzationAction______preUrl================" + session.getAttribute("PRE_URL"));
        return "redirect:" + url;
    }

    private void setLoginInfo(Model model, String userName, String tinfo) {
        model.addAttribute("userName", userName);
        model.addAttribute("tinfo", tinfo);
    }

    @RequestMapping(value = "/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "/auth/index";
    }
}
